package com.phoenix.hotdepoly.deploy;

import com.phoenix.hotdepoly.service.DynamicService;

import java.io.IOException;
import java.nio.file.*;

public class ClassReloader {

    private volatile DynamicService dynamicService;

    public ClassReloader() {
        reload();
        watch();
    }

    public DynamicService getDynamicService() {
        return dynamicService;
    }

    private void reload() {
        try {
            Path classFile = Paths.get("hot/classes/com/phoenix/hotdepoly/service/DynamicService.class");
            HotSwapClassLoader loader = new HotSwapClassLoader();
            Class<?> clazz = loader.loadClassFromFile("com.phoenix.hotdepoly.service.DynamicService", classFile);
            dynamicService = (DynamicService) clazz.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void watch(){
        new Thread(() ->{
            try {
                WatchService watchService = FileSystems.getDefault().newWatchService();
                Path path = Paths.get("hot/classes/com/example/demo2/service");
                path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
                while (true) {
                    WatchKey key = watchService.take();
                    for (WatchEvent<?> event : key.pollEvents()) {
                        if (event.context().toString().equals("DynamicService.class")) {
                            reload();
                        }
                    }
                    key.reset();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();

    }
}
